package com.bor.gb.rest.handlers;


import com.bor.gb.core.exception.AppException;
import com.bor.gb.db.services.AlertService;
import com.bor.gb.db.services.UserService;
import com.bor.gb.rest.util.Response;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.atomic.AtomicLong;

@RestController
@RequestMapping("/v01/user")
public class UserRestController {
    private static final Log log = LogFactory.getLog(UserRestController.class);


    private final AtomicLong counter = new AtomicLong();

    @Autowired
    private UserService userService;

    @RequestMapping(method = RequestMethod.GET, value = "/session")
    public
    @ResponseBody
    Object getSessionStatus() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        return auth;
    }

    /**
     * Sign Up users endpoint
     *
     * @param name
     * @param password
     * @return register status
     */
    @RequestMapping(method = RequestMethod.PUT, value = "/signup")
    public
        @ResponseBody
    ResponseEntity signUp(@RequestParam(value = "email", required = true) String name,
                          @RequestParam(value = "password", required = true) String password) {

        log.info("User is" + name + " logging in ");
        AlertService.info("user " + name + " logging");
        try {
            userService.createNewUser(name, password);
            return new ResponseEntity<String>(HttpStatus.OK);
        } catch (AppException e) {

            return new ResponseEntity<String>(e.getMessage(), HttpStatus.BAD_REQUEST);
        }
    }

    @RequestMapping(method = RequestMethod.GET, value = "/activate")
    public
    @ResponseBody
    ResponseEntity activate(@RequestParam(value = "id", required = true) String id,
                            @RequestParam(value = "key", required = true) String lockKey) {
        try {
            userService.unlockUser(id, lockKey);
            return new ResponseEntity<String>(HttpStatus.OK);
        } catch (AppException e) {

            return new ResponseEntity<String>(e.getMessage(), HttpStatus.BAD_REQUEST);
        }

    }

    @RequestMapping(method = RequestMethod.GET, value = "/signin")
    public
    @ResponseBody
    ResponseEntity loginGet() {
        return new Response.Error("login uses POST", HttpStatus.OK);
    }

}


